﻿using GoogleMobileAds.Api;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RewardedVideoButton : MonoBehaviour
{
    private const string ACTION_NAME = "rewarded_video";

    private void OnEnable()
    {
        Timer.Schedule(this, 0.1f, AddEvents);
    }

    private void AddEvents()
    {
#if UNITY_ANDROID || UNITY_IOS
        if (AdmobController.instance.rewardBasedVideo != null)
        {
            AdmobController.instance.rewardBasedVideo.OnAdRewarded += HandleRewardBasedVideoRewarded;
        }
#endif
    }

    public void OnClick()
    {
        //if (IsAvailableToShow())
        //{
        //    AdmobController.instance.ShowRewardBasedVideo();
        //}
        //else if (!IsActionAvailable())
        //{
        //    int remainTime = (int)(GameConfig.instance.rewardedVideoPeriod - CUtils.GetActionDeltaTime(ACTION_NAME));
        //    Toast.instance.ShowMessage("等待 " + remainTime + " 后可再次获取");
        //}
        //else
        //{
        //    Toast.instance.ShowMessage("目前无可播放广告, 请稍等..");
        //}

        Sound.instance.PlayButton();

        string videoAdid = VideData.Instance.GetVide();
        TTSDK.TTRewardedVideoAd r = AdMgr.Instance.ShowVideoAdNew(videoAdid);

        //创建激励视频关闭回调
        r.OnClose += (bol, val) =>
        {
            Debug.Log("关闭广告 ，是否已经看完" + bol);
            //看完广告获得提示
            if (bol)
            {
                GameManager.Apple += 50;
                MaidianNew.MaidianBackCallback(" ");
                Debug.Log("广告看完");
            }
            else
            {
                Debug.Log("广告未看完");
            }
        };

        //创建报错回调  
        r.OnError += (code, errorMessage) =>
        {
            Toast.instance.ShowMessage("广告发生错误");
            Debug.Log("code:" + code + "错误信息：" + errorMessage);
        };

        //展示广告（新版本必须调用，不然无法展示出来广告）
        r.Show();
    }

    public void HandleRewardBasedVideoRewarded(object sender, Reward args)
    {
        int amount = GameConfig.instance.rewardedVideoAmount;
        GameManager.Apple += amount;
        Toast.instance.ShowMessage("你已收到 " + amount + " 个货币", 2);
        CUtils.SetActionTime(ACTION_NAME);
    }

    public bool IsAvailableToShow()
    {
        return IsActionAvailable() && IsAdAvailable();
    }

    private bool IsActionAvailable()
    {
        return CUtils.IsActionAvailable(ACTION_NAME, GameConfig.instance.rewardedVideoPeriod);
    }

    private bool IsAdAvailable()
    {
        if (AdmobController.instance.rewardBasedVideo == null) return false;
        bool isLoaded = AdmobController.instance.rewardBasedVideo.IsLoaded();
        return isLoaded;
    }

    private void OnDisable()
    {
#if UNITY_ANDROID || UNITY_IOS
        if (AdmobController.instance.rewardBasedVideo != null)
        {
            AdmobController.instance.rewardBasedVideo.OnAdRewarded -= HandleRewardBasedVideoRewarded;
        }
#endif
    }
}
